package com.xjscrm.console.chat.core.impl;

import com.xjscrm.common.entity.WwCustomer;
import com.xjscrm.common.entity.WwGroupMember;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.dto.ChatRecordDTO;
import com.xjscrm.console.chat.frame.recv.RPullRecordMsg;
import com.xjscrm.console.chat.frame.send.SPullRecordResultMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.dto.chat.ChatTalkRecordQueryDTO;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.mapper.WwGroupMemberMapper;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.wwCustomer.WwCustomerService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author mingyang.chen create in 2024/3/12 09:41
 */
@Component
@Slf4j
public class ChatPullRecordMsgHandler extends ChatBaseMsgHandler<RPullRecordMsg> {

    @Autowired
    private ChatTalkRecordService chatTalkRecordService;
    @Autowired
    private ChatTalkSessionService chatTalkSessionService;
    @Autowired
    private WwCustomerService wwCustomerService;
    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;

    @Override
    public SResultMsg doHandle(RPullRecordMsg content, ChannelHandlerContext ctx) {

        SPullRecordResultMsg pullSessionResultMsg = new SPullRecordResultMsg();
        try {

            Long merId = content.getMerId();
            Long talkSessionId = content.getTalkSessionId();

            ChatTalkSession talkSession = chatTalkSessionService.getById(content.getMerId(), talkSessionId);
            if (Objects.isNull(talkSession)) {
                throw new BusinessException("聊天记录拉取失败: 会话未找到");
            }
            boolean isGroup = Objects.equals(talkSession.getType(), 111);
            String conversationId = talkSession.getConversationId();

            WwCustomer customer;
            if (!isGroup) {
                customer = wwCustomerService.getByWxId(merId, talkSession.getDeviceUniqueId(), conversationId);
                if (Objects.isNull(customer)) {
                    throw new BusinessException("聊天记录拉取失败: 客户未找到");
                }
            } else {
                customer = new WwCustomer();
            }

            ChatTalkRecordQueryDTO query = new ChatTalkRecordQueryDTO();
            query.setMerId(content.getMerId());
            query.setTalkSessionId(talkSessionId);
            query.setPullCount(content.getPullCount());
            query.setPullTime(content.getPullTime());
            query.setContentType(content.getContentType());
            List<ChatTalkRecord> pullRecords = chatTalkRecordService.listByTime(query);

            if (ObjectUtils.isEmpty(pullRecords)) {
                return pullSessionResultMsg;
            }
            Map<String, WwGroupMember> collect = new HashMap<>();
            if (isGroup) {
                List<String> wxIds = pullRecords.stream().map(ChatTalkRecord::getSendWxId).distinct().collect(Collectors.toList());
                List<WwGroupMember> wwGroupMembers = wwGroupMemberMapper.selectListByGroupWxIdAndWxid(talkSession.getConversationId(), wxIds, merId);
                collect = wwGroupMembers.stream().collect(Collectors.toMap(WwGroupMember::getWxid, Function.identity()));
            }

            Map<String, WwGroupMember> finalCollect = collect;
            List<ChatRecordDTO> result = pullRecords.stream().map(item -> {
                ChatRecordDTO chatRecordDTO = new ChatRecordDTO();
                BeanUtils.copyProperties(item, chatRecordDTO);
                chatRecordDTO.parse();
                if (isGroup) {
                    chatRecordDTO.setHeadImgUrl(finalCollect.get(item.getSendWxId()).getHimg());
                    chatRecordDTO.setSendWxName(finalCollect.get(item.getSendWxId()).getNick());
                } else {
                    chatRecordDTO.setHeadImgUrl(customer.getHeadImgUrl());
                    if (StringUtils.isBlank(chatRecordDTO.getSendWxName())) {
                        chatRecordDTO.setSendWxName(customer.getNickname());
                    }
                }
                return chatRecordDTO;
            }).collect(Collectors.toList());

            pullSessionResultMsg.setRecords(result);
        } catch (Exception e) {
            log.error("拉取回话聊天记录失败", e);
            throw new BusinessException("拉取回话聊天记录失败");
        }
        return pullSessionResultMsg;
    }

    @Override
    public boolean checkMsg(RPullRecordMsg baseMsg) {
        return super.checkMsg(baseMsg) || !ObjectUtils.allNotNull(baseMsg.getPullCount(), baseMsg.getTalkSessionId());
    }

    @Override
    public Class<RPullRecordMsg> msgClass() {
        return RPullRecordMsg.class;
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_pull_record;
    }
}
